//
//  ServiceCollectionView.swift
//  home
//
//  Created by Yun Zeng on 2019/1/28.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import UIKit
import AudioToolbox

class ServiceCollectionView: UIView, UICollectionViewDataSource, UICollectionViewDelegate {

    var manager: ServiceModelManager!
    var controller: UIViewController?
    var services: UICollectionView!
    var panel: ServicePanelBase?
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        _ = self.manager.toggleAtIndex(index: indexPath.row)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.manager.customs.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ServiceCell.identifier, for: indexPath) as! ServiceCell
        cell.setService(service: self.manager.customs[indexPath.row]) { (service) in
            self.forceTouchAtIndex(index: indexPath.row, cell: cell)
        }
        return cell
    }
    
    func setServiceManager(manager: ServiceManager, update: Bool = true) {
        self.manager = ServiceModelManager(manager: manager)
        self.cellCount = self.manager.customs.count
        self.manager.onUpdate = { (index) in
            if let cell = self.servicesView.cellForItem(at: IndexPath(row: index, section: 0)) as? ServiceCell {
                cell.setService(service: self.manager.customs[index]) { (service) in
                    self.forceTouchAtIndex(index: index, cell: cell)
                }
            }
            if let p = self.panel, p.service == self.manager.customs[index].service {
                p.updateService()
            }
        }
        if update {
            self.servicesView.reloadData()
        }
    }
    
    fileprivate var servicesView: UICollectionView!
    init(frame: CGRect, manager: ServiceManager) {
        super.init(frame: CGRect())
        self.setServiceManager(manager: manager, update: false)
        
        let layout = FlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 4, left: 19, bottom: 0, right: 19)
        layout.itemSize = CGSize(width: 105, height: 105)
        layout.headerReferenceSize = CGSize(width: frame.width, height: 32)
        layout.minimumInteritemSpacing = 10.0
        layout.minimumLineSpacing = 11.0
        layout.estimatedItemSize = CGSize(width: 0, height: 0)
        
        services = UICollectionView(frame: .zero, collectionViewLayout: layout)
        services.isScrollEnabled = false
        services.dataSource = self
        services.delegate = self
        
        services.register(ServiceCell.self, forCellWithReuseIdentifier: ServiceCell.identifier)
        services.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: ServiceCollectionView.identifier)
        
        services.backgroundColor = UIColor.clear
        services.delaysContentTouches = false
        self.addSubview(services)
        
        let gesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
        gesture.minimumPressDuration = 0.5
        services.addGestureRecognizer(gesture)
        
        services.automaticallyAdjustsScrollIndicatorInsets = true
        services.translatesAutoresizingMaskIntoConstraints = false
        services.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        services.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
        services.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
        services.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
        
        self.servicesView = services
    }
    
    var contentHeight: Int?
    private var cellCount: Int = 0
    
    override func layoutSubviews() {
        super.layoutSubviews()
        // 计算单元格占用高度
        let width = self.subviews.first!.frame.width
        var count = (width - 19.0) / (105.0 + 10.0)
        let last = (width - 19.0).truncatingRemainder(dividingBy: (105.0 + 10.0))
        if last < (19.0 - 10.0) {
            count = count - 1
        }
        self.contentHeight = (105 + 10) * (cellCount / Int(count)) + 32 + 4
        if CGFloat(cellCount).truncatingRemainder(dividingBy: CGFloat(Int(count))) > 1.0 {
            self.contentHeight = self.contentHeight! + (105 + 10)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 表头
    static let identifier = "ServicesCollectionViewHeader"
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        var reusableView: UICollectionReusableView!
        if kind == UICollectionView.elementKindSectionHeader {
            reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ServiceCollectionView.identifier, for: indexPath)
            let label = UILabel(frame: CGRect(x: 22, y: 0, width: reusableView.frame.width-20, height: reusableView.frame.height))
            let attributes: [NSAttributedString.Key : Any] = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.bold),
                NSAttributedString.Key.kern: -0.36,
                NSAttributedString.Key.foregroundColor: UIColor.white]
            label.attributedText = NSAttributedString(string: "家居设备", attributes: attributes)
            label.textAlignment = NSTextAlignment.left
            reusableView.addSubview(label)
            // 文字阴影，让字体显得更白
            reusableView.layer.shadowColor = UIColor(red: 103/255, green: 103/255, blue: 103/255, alpha: 0.32).cgColor
            reusableView.layer.shadowOffset = CGSize.zero
            reusableView.layer.shadowRadius = 3.0
            reusableView.layer.shadowOpacity = 0.0
        }
        return reusableView
    }
}

// 滑动时图标回归静态
extension ServiceCollectionView {
    public func setStatic() {
        for cell in self.servicesView.visibleCells {
            if let service = cell as? ServiceCell {
                service.setStatic()
            }
        }
    }
}

extension ServiceCollectionView {
    func forceTouchAtIndex(index: Int, cell: ServiceCell) {
        let custom = self.manager.customs[index]
        let controller =  ServicePanelBase.getCustomPanel(cell: custom)
        controller.modalPresentationStyle = .formSheet
        controller.isModalInPresentation = false
        controller.preferredContentSize = CGSize(width: 375, height: 680)
        if custom.service.type == HMServiceType.airConditioner.rawValue
            || custom.service.type == HMServiceType.htSensor.rawValue
        || custom.service.type == HMServiceType.zigbeeCoordinator.rawValue
        || custom.service.type == HMServiceType.contactSensor.rawValue
        || custom.service.type == HMServiceType.outlet.rawValue
        || custom.service.type == HMServiceType.clock.rawValue {
            controller.preferredContentSize = CGSize(width: 375, height: 740)
        }
        self.panel = controller
        controller.onBack = {
            self.panel = nil
            cell.setStatic()
        }
        cell.isPlayed = true
        AudioServicesPlaySystemSound(1520)
        self.controller?.present(controller, animated: true) 
    }
    
    @objc func handleLongPress(gestureRecognizer: UILongPressGestureRecognizer) {
        let pos = gestureRecognizer.location(in: self.services)
        guard let index = services.indexPathForItem(at: pos) else {
            return
        }
        guard let cell = services.cellForItem(at: index) as? ServiceCell else {
            return
        }
        if cell.isPlayed {
            return
        }
        self.forceTouchAtIndex(index: index.row, cell: cell)
    }
    
}

